<?php

namespace App\Dao\Ocean;

use Yj\Daos\BaseDaos;
use App\Model\Ocean\OceanRankingSetting;
use Hyperf\Database\Model\Builder;
use Yj\Daos\Verify;
use Hyperf\Utils\Collection;

/**
 * @var OceanRankingSetting
 * @method $this params($params)
 */
class OceanRankingSettingDao extends BaseDaos
{
    public function searchParams(Collection $params)
    {
            $search = $this->getSearch();
            $params->check('id',function($id) use ($search) {
                $search->where('id',$id);
            });
            return $search;
    }

    public function lists(Collection $params)
    {
            $data = $this->params($params)->orderBy("rank")->getList();
            return $data;
    }

    public function check($id,$rank){
        if($rank<0){
            _Error('名次不能小于0');
        }
        if($this->getSearch()->tap(function ($query)use($id,$rank){
            if($id>0){
                $query->where('id','<>',$id);
            }
        })->where('rank',$rank)->exists()){
            _Error('该名次已经存在');
        }
    }

    public function add(Collection $params)
    {
          $this->check(0,$params->get('rank'));
            $data = $this->create($params->toArray());
            return $data;
    }

    public function edit(int $id, Collection $params)
    {
            $this->check($id,$params->get('rank'));
            $data = $this->params(_Collect(["id"=>$id]))->firstOrError();
            $data->fill($params->toArray());
            return $data->save();
    }

    public function read(int $id)
    {
           $data = $this->params(_Collect(["id"=>$id]))->firstOrError();
           return $data;
    }

    public function del(int $id)
    {
            $data = $this->params(_Collect(["id"=>$id]))->firstOrError();
            return $data->delete();
    }
}
